package com.yc.damai.web;

import com.yc.damai.entity.DmUser;
import com.yc.damai.util.QRCodeUtil;
import com.yc.login.vo.Result;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;

/**
 * 扫码登录
 * 用手机替代PC账号输入完成授权认证的过程
 * 前提: 手机端APP长期在线( 安卓, HTML )
 * 1. PC如果要登录, 打开二维码图片
 *      服务为PC生成一个唯一的编码(UUID), 对应扫描状态
 * 2. 手机扫码, 二维码还原成一个字符串 => URL => 访问服务器
 *      修改PC的编码的状态, 并且将用户信息存入状态中
 * 3. PC端监控扫码状态, 一旦扫码完成, 就会获取用户信息, 实现登录
 *      1) ajax 轮询 : 每隔 1 秒查询服务器扫描状态
 *      2) websocket: 服务器主动推送扫描结果
 *
 */
@RestController
public class ScanLogin {

    // 存放二维码和状态 TODO 存入Reids
    Map<String,Object> qrMap = new Hashtable<>();

    // PC 端
    @RequestMapping(path = "createQr", produces = MediaType.IMAGE_PNG_VALUE)
    public void createQr(HttpSession session,
                           OutputStream out) throws Exception {
        String qrcode = UUID.randomUUID().toString();
        session.setAttribute("qrcode", qrcode);
        qrMap.put(qrcode,0);
        String url = "http://192.168.15.225/damai-user/scanQr?qrcode=" + qrcode;
        System.out.println("url = " + url);
        QRCodeUtil.encode(url,"d:/095111izhgxmsjm88xwxfz.gif", out, true);
    }

    // 手机端, 必须要登录
    @RequestMapping("scanQr")
    public Result scanQr(String qrcode,
                         @SessionAttribute(required = false) DmUser loginedUser){
        if(loginedUser == null){
            return new Result(0 ,"请先登录系统!", null);
        }
        if (qrMap.containsKey(qrcode) == false) {
            return new Result(-1 ,"该二维码已经过期!", null);
        }
        System.out.println("---------------" + qrcode);
        // 扫码成功!
        qrMap.put(qrcode, loginedUser);
        return new Result(1 ,"扫码成功!", null);
    }

    // 通知 PC 端扫码成功!
    // ajax 轮询
    @RequestMapping("refreshQr")
    public Result refreshQr(@SessionAttribute(required = false) String qrcode,
                            HttpSession session){

        if (qrcode == null || qrMap.containsKey(qrcode) == false) {
            return new Result(-1 ,"该二维码已经过期!", null);
        }
        Object state = qrMap.get(qrcode);
        if(state instanceof DmUser){
            session.setAttribute("loginedUser", state);
            session.removeAttribute("qrcode");
            qrMap.remove(qrcode);
            return new Result(1 ,"登录成功!", state);
        }
        return new Result(0 ,"还未扫码!", null);
    }
}
